package at.fhooe.engine.event;

import java.util.ArrayList;
import java.util.HashMap;

import at.fhooe.engine.event.events.Event;

public class SaveListenerStrategy implements ListenerStrategy {

	private HashMap<String, ArrayList<EventListener>> m_listeners;

	public SaveListenerStrategy() {
		m_listeners = new HashMap<String, ArrayList<EventListener>>();
	}

	@Override
	public void removeListener(EventListener eventListener, String eventType) {
		ArrayList<EventListener> listenerList = m_listeners.get(eventType);

		if(listenerList != null) {
			listenerList.remove(eventListener);
		}
	}

	@Override
	public void addListener(EventListener eventListener, String eventType) {
		ArrayList<EventListener> listenerList = m_listeners.get(eventType);

		if (listenerList == null) {
			listenerList = new ArrayList<EventListener>();
			listenerList.add(eventListener);
			m_listeners.put(eventType, listenerList);
		} else {
			if(listenerList.contains(eventListener)) {
				throw new RuntimeException("Listener already added!");
			} else {
				listenerList.add(eventListener);
			}
		}
	}

	@Override
	public void fireEvent(Event event) {
		// copy list, since listeners can be removed when state changes
		ArrayList<EventListener> tmpListeners = m_listeners.get(event.getEventId());

		if (tmpListeners != null) {
			ArrayList<EventListener> listenersForProcessing = new ArrayList<EventListener>(tmpListeners);

			for (EventListener listener : listenersForProcessing) {
				event.processEvent(listener);
			}

			listenersForProcessing.clear();
		}
	}

	@Override
	public void removeAllListeners() {
		for (String eventType : m_listeners.keySet()) {
			m_listeners.get(eventType).clear();
		}
		m_listeners.clear();
	}

}
